/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "imageknife_node_internal.h"
#include "border_option_napi.h"
#include "imageknife_dispatcher.h"
#include "imageknife_node_animator.h"
#include "imageknife_trace.h"
#include "option/imageknife_option_napi.h"
#include "request/imageknife_request_internal.h"
#include "imageknife_node_image.h"
#include "imageknife_internal.h"
#include "downsampling/down_sampler.h"
#include "render/imageknife_render.h"
#include "common.h"

namespace ImageKnifePro {

ImageKnifeNodeInternal::ImageKnifeNodeInternal(std::shared_ptr<ImageKnifeOption> option,
    ArkUI_NodeHandle handle, bool customMeasure) : ArkUINode(handle), customMeasure_(customMeasure)
{
    ImageKnifeTrace trace("Create ImageKnifeNodeInternal");
    trace.StartSyncTrace();
    Init(option);

    if (!customMeasure_) {
        GetNodeAPI()->registerNodeEvent(handle, NODE_EVENT_ON_AREA_CHANGE, 0, nullptr);
    }
}

void ImageKnifeNodeInternal::Init(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK(option == nullptr, "Null ImageKnifeOption");
    imageKnifeRequest_ = std::make_shared<ImageKnifeRequestInternal>(option, GetNodeVersion());
    border_ = option->border;
    objectFit_ = option->objectFit;
    placeholderObjectFit_ = option->placeholderObjectFit;
    thumbnailObjectFit_ = option->thumbnailObjectFit;
    errorObjectFit_ = option->errorObjectFit;
    colorFilter_ = option->colorFilter;
    resizeable_ = option->resizeable;
    SetBorder();

    GetNodeAPI()->setUserData(handle, this);
    GetNodeAPI()->addNodeEventReceiver(handle, OnNodeEvent);

    ArkUI_NumberValue numValue = {.f32 = 0};
    ArkUI_AttributeItem item = {.value = &numValue, .size = 1};
    GetNodeAPI()->setAttribute(handle, NODE_VISIBLE_AREA_CHANGE_RATIO, &item);
    GetNodeAPI()->registerNodeEvent(handle, NODE_EVENT_ON_VISIBLE_AREA_CHANGE, 0, nullptr);
}

ImageKnifeNodeInternal::~ImageKnifeNodeInternal()
{
    ImageKnifeTrace trace("Destroy ImageKnifeNodeInternal", componentId_);
    trace.StartSyncTrace();
    IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s]  ImageNode Destroy", componentId_.c_str());
    ReleaseDecodeSvgTasks();
    if (!customMeasure_) {
        GetNodeAPI()->unregisterNodeEvent(handle, NODE_EVENT_ON_AREA_CHANGE);
    }
    GetNodeAPI()->unregisterNodeEvent(handle, NODE_EVENT_ON_VISIBLE_AREA_CHANGE);
    GetNodeAPI()->removeNodeEventReceiver(handle, OnNodeEvent);
    GetNodeAPI()->disposeNode(handle);
}

// static
void ImageKnifeNodeInternal::OnNodeEvent(ArkUI_NodeEvent *event)
{
    auto nodeHandle = OH_ArkUI_NodeEvent_GetNodeHandle(event);
    ImageKnifeNodeInternal *node = reinterpret_cast<ImageKnifeNodeInternal *>(GetNodeAPI()->getUserData(nodeHandle));
    auto eventType = OH_ArkUI_NodeEvent_GetEventType(event);

    switch (eventType) {
        case NODE_EVENT_ON_AREA_CHANGE:
            node->OnAreaChange(event);
            break;
        case NODE_EVENT_ON_VISIBLE_AREA_CHANGE:
            node->OnVisibleAreaChange(event);
        default:
            node->OnDerivedNodeEvent(event);
            return;
    }
}

void ImageKnifeNodeInternal::OnVisibleAreaChange(ArkUI_NodeEvent *event)
{
    auto componentEvent = OH_ArkUI_NodeEvent_GetNodeComponentEvent(event);
    if (componentEvent->data[0].i32 > 0) {
        IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] On Node Show", GetComponentId().c_str());
        OnNodeShow();
    } else {
        IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] On Node Hide", GetComponentId().c_str());
        OnNodeHide();
    }
}

void ImageKnifeNodeInternal::OnNodeShow()
{
}

void ImageKnifeNodeInternal::OnNodeHide()
{
}

void ImageKnifeNodeInternal::OnAreaChange(ArkUI_NodeEvent *event)
{
    enum ComponentEventDataIndex {
        OLD_WIDTH_INDEX = 0,
        OLD_HEIGHT_INDEX = 1,
        WIDTH_INDEX = 6,
        HEIGHT_INDEX = 7,
    };

    auto componentEvent = OH_ArkUI_NodeEvent_GetNodeComponentEvent(event);
    width_ = componentEvent->data[WIDTH_INDEX].f32;
    height_ = componentEvent->data[HEIGHT_INDEX].f32;
    if ((width_ != componentEvent->data[OLD_WIDTH_INDEX].f32) ||
        (height_ != componentEvent->data[OLD_HEIGHT_INDEX].f32)) {
        imageKnifeRequest_->SetComponentSize(GetComponentSize());
        OnMeasureComplete();
        ImageKnifeDispatcher::GetInstance().EnqueueMainSrc(imageKnifeRequest_);
    }
}

void ImageKnifeNodeInternal::RemoveBorder()
{
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_WIDTH);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_WIDTH_PERCENT);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_RADIUS);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_RADIUS_PERCENT);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_STYLE);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_COLOR);
}

void ImageKnifeNodeInternal::SetBorder()
{
    if (border_ == nullptr) {
        // 移除旧的border设置
        RemoveBorder();
        return;
    }

    if (!border_->width.empty()) {
        SetBorderProperty(border_->width, NODE_BORDER_WIDTH);
    } else {
        // 如果percentageWidth为空，则width都为空，设置为空符合效果，两者本是一体
        SetBorderProperty(border_->percentageWidth, NODE_BORDER_WIDTH_PERCENT);
    }

    if (!border_->radius.empty()) {
        SetBorderProperty(border_->radius, NODE_BORDER_RADIUS);
    } else {
        // 如果percentageRadius为空，则radius都为空，设置为空符合效果，两者本是一体
        SetBorderProperty(border_->percentageRadius, NODE_BORDER_RADIUS_PERCENT);
    }

    SetBorderProperty(border_->color, NODE_BORDER_COLOR);
    SetBorderProperty(border_->style, NODE_BORDER_STYLE);
}

void ImageKnifeNodeInternal::Update(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr);
    if ((imageKnifeRequest_->GetStatus() != ImageKnifeRequest::Status::COMPLETE &&
        imageKnifeRequest_->GetStatus() != ImageKnifeRequest::Status::PROGRESS) || nodeState_ == CLEARED) {
        // 之前的加载请求失败或取消， 或组件复用导致图片清空， 需重置key进行重新加载
        mainSrcKey_ = "";
    } else if (!IsUpdateNecessary(option)) {
        // 图片无需加载，但border等属性可能需要更新
        UpdateAttribute(option);
        return;
    }

    Reuse();
    ImageKnife::GetInstance().CancelRequest(imageKnifeRequest_);

    ImageKnifeTrace trace("Update", componentId_);
    trace.StartSyncTrace();
    IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s]  ImageNode Update", componentId_.c_str());
    auto request = std::make_shared<ImageKnifeRequestInternal>(option, GetNodeVersion());
    request->SetComponentId(componentId_);
    request->SetComponentSize(GetComponentSize());
    imageKnifeRequest_ = request;
    UpdateDerivedNodeEvent(option);

    border_ = option->border;
    objectFit_ = option->objectFit;
    placeholderObjectFit_ = option->placeholderObjectFit;
    thumbnailObjectFit_ = option->thumbnailObjectFit;
    errorObjectFit_ = option->errorObjectFit;
    colorFilter_ = option->colorFilter;
    resizeable_ = option->resizeable;
    SetBorder();
    ImageKnifeInternal::GetInstance().Execute(imageKnifeRequest_);
}

void ImageKnifeNodeInternal::DisposeNode()
{
    ImageKnifeInternal::GetInstance().CancelRequest(imageKnifeRequest_);
    if (contentSlot_ != nullptr && nodeUploaded_) {
        OH_ArkUI_NodeContent_RemoveNode(contentSlot_, handle);
    }

    ImageKnifeInternal::GetInstance().DisposeImageNode(componentId_);
    // 避免超长帧播放阻塞析构
    TerminateAnimation();
}

void ImageKnifeNodeInternal::Execute()
{
    ImageKnifeInternal::GetInstance().Execute(GetImageKnifeRequest());
    UploadNodeHandle();
}

// 父类空实现，仅部分组件支持
void ImageKnifeNodeInternal::ContentTransition(ContentTransitionType effectType)
{
}

void ImageKnifeNodeInternal::Adaptable(bool adaptable)
{
    adaptable_ = adaptable;
}

bool ImageKnifeNodeInternal::IsAdaptable() const
{
    return adaptable_;
}

void ImageKnifeNodeInternal::SyncLoad(bool syncLoad)
{
    IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr);
    imageKnifeRequest_->SyncLoad(syncLoad);
}

void ImageKnifeNodeInternal::SetWidth(float width)
{
    ArkUI_NumberValue value = {.f32 = width};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_WIDTH, &item);
}

void ImageKnifeNodeInternal::SetPercentWidth(float percent)
{
    ArkUI_NumberValue value = {.f32 = percent};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_WIDTH_PERCENT, &item);
}

void ImageKnifeNodeInternal::SetHeight(float height)
{
    ArkUI_NumberValue value = {.f32 = height};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_HEIGHT, &item);
}

void ImageKnifeNodeInternal::SetPercentHeight(float percent)
{
    ArkUI_NumberValue value = {.f32 = percent};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_HEIGHT_PERCENT, &item);
}

void ImageKnifeNodeInternal::SetMainSrcKey(std::string key)
{
    mainSrcKey_ = key;
}

void ImageKnifeNodeInternal::SetContentSlot(ArkUI_NodeContentHandle contentSlot)
{
    contentSlot_ = contentSlot;
}

bool ImageKnifeNodeInternal::UploadNodeHandle()
{
    if (nodeUploaded_) {
        return true;
    }

    if (contentSlot_ != nullptr) {
        nodeUploaded_ = true;
        // 添加Native组件到NodeContent上用于挂载显示
        OH_ArkUI_NodeContent_AddNode(contentSlot_, handle);
    }
    return false;
}

Image_Size ImageKnifeNodeInternal::GetComponentSize()
{
    // vp to px
    float pixels = GetDisplayDensity();
    return {static_cast<uint32_t>(std::round(width_ * pixels)),
            static_cast<uint32_t>(std::round(height_ * pixels))};
}

bool ImageKnifeNodeInternal::IsDecodeSvgAfterMeasure(std::shared_ptr<ImageKnifeTaskInternal> task)
{
    IMAGE_KNIFE_CHECK_RETURN(task == nullptr, false);
    std::lock_guard<std::mutex> guard(measureLock_);
    if (measureComplete_) {
        return false;
    }

    decodeSvgTasks_.push_back(task);
    return true;
}

void ImageKnifeNodeInternal::OnMeasureComplete()
{
    std::lock_guard<std::mutex> guard(measureLock_);
    measureComplete_ = true;

    if (decodeSvgTasks_.empty()) {
        return;
    }

    for (auto it = decodeSvgTasks_.begin(); it != decodeSvgTasks_.end(); it++) {
        std::shared_ptr<ImageKnifeTaskInternal> task = *it;
        if (task == nullptr) {
            IMAGE_KNIFE_LOG(LOG_ERROR, "[ID:%{public}s]  Decode Svg On Measure Complete, task is nullptr",
                            componentId_.c_str());
            continue;
        }

        // 发起svg解码
        IMAGE_KNIFE_LOG(LOG_DEBUG, "%{public}s Decode Svg On Measure Complete", task->GetTaskInfo().c_str());
        TaskWorker::GetInstance()->PushTask([](std::shared_ptr<ImageKnifeTaskInternal> task) {
            ImageKnifeDispatcher::GetInstance().ProcessRemainingTask(task);
            ImageKnifeDispatcher::GetInstance().OnTaskComplete(task, IJobQueue::EndPhase::DECODING);
            }, nullptr, task, ImageKnifeQOS::USER_INITIATED);
    }
    decodeSvgTasks_.clear();
}

void ImageKnifeNodeInternal::ReleaseDecodeSvgTasks()
{
    std::lock_guard<std::mutex> guard(measureLock_);
    measureComplete_ = true;

    if (decodeSvgTasks_.empty()) {
        return;
    }

    // 如果组件析构时有未执行的task，标记取消
    for (auto it = decodeSvgTasks_.begin(); it != decodeSvgTasks_.end(); it++) {
        std::shared_ptr<ImageKnifeTaskInternal> task = *it;
        if (task == nullptr) {
            continue;
        }

        auto request = task->GetImageKnifeRequestInternal();
        if (request == nullptr) {
            continue;
        }

        request->Destroy();
        task->cancelInfo = "Component Dispose";
        TaskWorker::GetInstance()->PushTask([](std::shared_ptr<ImageKnifeTaskInternal> task) {
            ImageKnifeDispatcher::GetInstance().OnTaskComplete(task, IJobQueue::EndPhase::DECODING);
            }, nullptr, task, ImageKnifeQOS::USER_INITIATED);
    }
    decodeSvgTasks_.clear();
}

bool ImageKnifeNodeInternal::IsUpdateNecessary(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK_RETURN(option == nullptr, false, "Null ImageKnifeOption");
    if (option->loadSrc.GetType() == DataType::UNDEFINED) {
        IMAGE_KNIFE_LOG(LOG_ERROR, "[ID:%{public}s] Main Source Not Set", componentId_.c_str());
        return false;
    }

    if (option->loadSrc.GetType() == DataType::PIXELMAP) {
        IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] Main Source Update By Pixelmap", componentId_.c_str());
        mainSrcKey_.clear();
        return true;
    }

    CacheKeyGenerator::MemoryKeyParams params = {.imageSource = &option->loadSrc, .type = ImageRequestType::MAIN_SRC,
                                                 .signature = option->signature, .isAnimator = IsAnimator(),
                                                 .orientation = option->orientation,
                                                 .dynamicRange = option->dynamicRange};
    if (option->multiTransformation != nullptr) {
        params.transformationInfo = option->multiTransformation->GetTransformInfo();
    } else if (option->transformation != nullptr) {
        params.transformationInfo = option->transformation->GetTransformInfo();
    }

    if (option->context.config != nullptr) {
        params.colorMode = option->context.config->colorMode;
    }

    params.downSamplingInfo = DownSampler::GetDownSamplingInfo(GetComponentSize(), option->downSampling);
    auto generator = ImageKnifeInternal::GetInstance().GetCacheKeyGenerator();
    IMAGE_KNIFE_CHECK_RETURN(generator == nullptr, false);

    std::string key = generator->GenerateMemoryKey(params);
    if (key != mainSrcKey_) {
        mainSrcKey_ = key;
        return true;
    }

    IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] Main Source not change, Update Is Unnecessary", componentId_.c_str());
    return false;
}

std::string ImageKnifeNodeInternal::GetMainSrcKey() const
{
    return mainSrcKey_;
}

void ImageKnifeNodeInternal::UpdateAttribute(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK(option == nullptr);
    IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr);

    // 图片加载已经完成， 属性变更需要立即设置
    bool applyNow = imageKnifeRequest_->GetStatus() == ImageKnifeRequest::Status::COMPLETE;

    if (option->objectFit != objectFit_) {
        objectFit_ = option->objectFit;
        if (applyNow) {
            FitImage(option->objectFit);
        }
    }

    placeholderObjectFit_ = option->placeholderObjectFit;
    thumbnailObjectFit_ = option->thumbnailObjectFit;
    errorObjectFit_ = option->errorObjectFit;

    if (option->colorFilter != nullptr && colorFilter_ != option->colorFilter) {
        colorFilter_ = option->colorFilter;
        if (applyNow) {
            SetColorFilter(option->colorFilter);
        }
    } else if (colorFilter_ != nullptr) {
        // 当前取消colorFilter, 但之前设置了colorFilter
        colorFilter_ = nullptr;
        if (applyNow) {
            RemoveColorFilter();
        }
    }

    if (IsResizeableOptionChanged(option)) {
        resizeable_ = option->resizeable;
        if (applyNow) {
            if (resizeable_ == nullptr) {
                RemoveResizeableOption();
            } else {
                SetResizeableOption(resizeable_);
            }
        }
    }

    // 非图片组件属性，通用属性更新
    if (IsBorderChanged(option)) {
        border_ = option->border;
        SetBorder();
        if (applyNow)  {
            //  border更新需要刷新图片资源
            RefreshImage();
        }
    }

    if (applyNow) {
        RefreshDrawing();
    }
}

void ImageKnifeNodeInternal::SetResizeableOption(std::shared_ptr<ResizableOption> resizeable)
{
}

void ImageKnifeNodeInternal::RemoveResizeableOption()
{
}

bool ImageKnifeNodeInternal::IsResizeableOptionChanged(std::shared_ptr<ImageKnifeOption> option)
{
    if (option->resizeable != nullptr) {
        if (resizeable_ == nullptr) {
            return true;
        } else if (option->resizeable->left != resizeable_->left ||
                   option->resizeable->right != resizeable_->right ||
                   option->resizeable->top != resizeable_->top ||
                   option->resizeable->bottom != resizeable_->bottom) {
            // 任意resizeable属性发生变更
            return true;
        }
    } else if (resizeable_ != nullptr) {
        return true;
    }

    return false;
}

bool ImageKnifeNodeInternal::IsBorderChanged(std::shared_ptr<ImageKnifeOption> option)
{
    if (option->border != nullptr) {
        if (border_ == nullptr) {
            return true;
        } else if (!CompareBorderProperty(option->border->width, border_->width) ||
                   !CompareBorderProperty(option->border->percentageWidth, border_->percentageWidth) ||
                   !CompareBorderProperty(option->border->radius, border_->radius) ||
                   !CompareBorderProperty(option->border->percentageRadius, border_->percentageRadius) ||
                   !CompareBorderProperty(option->border->style, border_->style) ||
                   !CompareBorderProperty(option->border->color, border_->color)) {
            // 任意border属性发生变更
            return true;
        }
    } else if (border_ != nullptr) {
        return true;
    }

    return false;
}

void ImageKnifeNodeInternal::ApplyAttribute(ImageRequestType type)
{
    switch (type) {
        case ImageRequestType::MAIN_SRC:
            FitImage(objectFit_);
            break;
        case ImageRequestType::PLACE_SRC:
            FitImage(placeholderObjectFit_);
            break;
        case ImageRequestType::THUMBNAIL_SRC:
            FitImage(thumbnailObjectFit_);
            break;
        case ImageRequestType::ERROR_SRC:
            FitImage(errorObjectFit_);
            break;
        default:
            IMAGE_KNIFE_LOG(LOG_ERROR, "Wrong Image Request Type (Apply Attribute)");
            break;
    }

    if (colorFilter_ != nullptr && type == ImageRequestType::MAIN_SRC) {
        SetColorFilter(colorFilter_);
    } else {
        RemoveColorFilter();
    }

    if (resizeable_ != nullptr && type == ImageRequestType::MAIN_SRC) {
        SetResizeableOption(resizeable_);
    } else {
        RemoveResizeableOption();
    }
}
} // end of namespace